
/***************************************************************************************
****************************************************************************************
* FILE		: battery.c
* Description	: 
*			  
* Copyright (c) 2020 by Simlife. All Rights Reserved.
* 
* History:
* Version		Name		Date				Description
   0.1		Alen			2020/05/07		Initial Version
   
****************************************************************************************
****************************************************************************************/

#include "includes.h"

void initBatteryAdcControlPin(void)
{
	batteryAdcTypeControl |= batteryAdcPin;			 // input
	batteryAdcPullUpControl &= batteryAdcPinReverse; // no pull up
}

void initChargeCheckControlPin(void)
{
	chargeCheckTypeControl |= chargeCheckPin;		   //input
	chargeCheckPullUpControl &= chargeCheckPinReverse; // no pull up

	chargeFullTypeControl |= chargeFullPin;	  // input
	chargeFullPullUpControl |= chargeFullPin; // pull up
}

#define LOW_POWER_TIMES 8

void batteryAdcProcess(void)
{

	U16 batteryAdc = getAdc12Bit();

	if (flagSystemLowPower)
	{
		if (batteryAdc < BATTERY_EMPTY_VALUE)
		{
			stTime.countLowPower++;
			if (stTime.countLowPower > LOW_POWER_TIMES)
			{
				flagSystemStatus = OFF;
				systemPower(OFF);
			}
		}
	}
	else
	{
		if (batteryAdc < BATTERY_LOW_VALUE)
		{
			stTime.countLowPower++;
			if (stTime.countLowPower > LOW_POWER_TIMES)
			{
				flagSystemLowPower = TRUE;
				stTime.countLowPower = 0;
			}
		}
		else
		{
			stTime.countLowPower = 0;
			flagSystemLowPower = FALSE;
		}
	}
}

#define CHARGE_TIME 50

void chargeCheckProcess(void) // 10ms call
{
	if (chargeCheckPortAndPin)
	{
		stTime.countChargeIn++;
		if (stTime.countChargeIn > CHARGE_TIME)
		{
			stTime.countChargeIn = CHARGE_TIME;
			flagSystemCharge = TRUE;
			if (flagSystemStatus)
			{
				flagSystemStatus = OFF;
				systemPower(OFF);
			}
			if (flagSystemLowPower)
			{
				flagSystemLowPower = FALSE;
			}
			initGreenLRControlPin();
			initChargeCheckControlPin();
			
		}

		if ((!flagSystemCharge) || flagSystemChargeFull) //未充电 和 充满电状态下
		{
			return;
		}

		if (chargeFullPortAndPin == 0)
		{
			stTime.countChargeFull++;
			if (stTime.countChargeFull > CHARGE_TIME)
			{
				flagSystemChargeFull = TRUE;
			}
		}
		else
		{
			stTime.countChargeFull = 0;
			flagSystemChargeFull = FALSE;
		}
	}
	else
	{
		if (flagSystemCharge)
		{
			stTime.countChargeFull = 0;
			flagSystemCharge = FALSE;
			flagSystemChargeFull = FALSE;
			initGreenNumberPin();
		}
		stTime.countChargeIn = 0;
	}
}
